# ----------------------------------------------------------------------------
#       Copyright (C) 2013-2014 Huynh Vi Lam  <domovilam@gmail.com>
#
#       This file is part of pimucha.
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------


import datetime,logging,logging.handlers,time

logger = logging.getLogger()



def rxeventlog(dev,logfile=None,socket=False,defaddr=('localhost','9020')):
    """
    Write event into logfile or to socket
    Write a line for each event
    Input event : a string of sequence of hex
    """
    if not dev.setup: return True
    if logfile:
        filehdlr = logging.FileHandler(logfile)
        formatterf = logging.Formatter('%(module)s - %(asctime)s %(levelname)s %(message)s')
        filehdlr.setFormatter(formatterf)
        logger.addHandler(filehdlr)
    elif socket:
        host,port = addr2host(defaddr)
        socketh = logging.handlers.SocketHandler(host,port)
        logger.addHandler(socketh)
    logger.setLevel(logging.DEBUG)
    while True:
        data = dev.rxevent()
        if data:
           logger.info("%s", data)


def rxeventq(dev,evtq):
    """
    Write event to Queue
    Write a line for each event
    Input event : a string of sequence of hex
    """
    if not dev.setup: return
    while True:
        data = dev.rxevent()
        if data:
            evtq.put_nowait(data)


def tstampdev(header):
    d = datetime.date.strftime(datetime.datetime.today(),"%Y-%m-%d %H:%M:%S").split()
    return [header, d[0], d[1]]
